import * as socket from 'socket.io'
import express from 'express'
import http from 'http'
import path from 'path'
const __dirname = path.resolve()
import cors from 'cors'

const log = console.log.bind(console)
// 创建一个应用，注意app其实就是一个函数，类似 function(req, res) {}
const app = express()
// 使用 cors 中间件允许跨域访问
app.use(cors())
app.use(express.static(path.join(__dirname)))
app.use(express.static('static'))
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*")
    res.header("Access-Control-Allow-Headers", "X-Requested-With")
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS")
    res.header("X-Powered-By", ' 3.2.1')
    //这段仅仅为了方便返回json而已
    res.header("Content-Type", "application/json;charset=utf-8")
    if (req.method == 'OPTIONS') {
        //让options请求快速返回
        res.sendStatus(200)
    } else {
        next()
    }
})

const server = http.createServer(app)
const io = new socket.Server(server)

const registerRoutes = (app, routes) => {
    routes.forEach(item => {
        let route = item
        app[route.method](route.path, route.func)
    })
}

import { indexRoutes } from './route/index.js'
registerRoutes(app, indexRoutes)

let chatRoomUsers = []
let registeredUsers = [
    {
        username: "1",
        password: "1",
        sex: "male",
        avatar: "images/avatar03.jpg",
    },
    {
        username: "2",
        password: "2",
        sex: "male",
        avatar: "images/avatar01.jpg",
    },
]

// 有新的客户端连接时触发
io.on('connection', function(socket) {
    // 监听用户断开连接
    socket.on('disconnect', () => {
        // 把当前用户信息从 chat room 中删除
        leaveFromChatRoom(socket)

        // 1.告诉所有人，有人离开了聊天室
        io.emit('deleteUser', {
            username: socket.username,
            avatar: socket.avatar
        })
        // 2.告诉所有人，userList发生更新
        io.emit('userList', chatRoomUsers)
    })

    socket.on('registerUser', data => {
        // 验证 data 是否存在
        let bo = true
        for (const key in data) {
            let item = data[key]
            if (!item) {
                socket.emit('errorMsg', { msg: '注册信息不完整' })
                bo = false
                return
            }
        }
        if (bo) {
            // 判断是否已经被注册
            let userIndex = registeredUsers.findIndex(item => item.username === data.username)
            if (userIndex > -1) {
                socket.emit('errorMsg', { msg: '该用户已被注册' })
            } else {
                registeredUsers.push(data)
                socket.emit('registerSuccess', data)
            }
        }
    })

    socket.on('login', data => {
        /**
         * 1. 先判断是否已经存在并登录
         * 2. 判断是否已经注册
         * 3. 登录成功
         */
        let user = chatRoomUsers.find(item => item.username === data.username)
        let regUser = registeredUsers.find(item => item.username === data.username)

        if (user) {
            // 表示用户存在
            socket.emit('loginError', { msg: '登陆失败, 用户已存在' })
        } else if (!regUser) {
            socket.emit('loginError', { msg: '登陆失败, 用户尚未注册' })
        } else {
            // 用户已注册
            if (regUser.password !== data.password) {
                socket.emit('loginError', { msg: '登陆失败, 密码错误' })
            } else {
                chatRoomUsers.push(regUser)
                socket.emit('loginSuccess', regUser)

                // 告诉所有人，有新用户加入到了聊天室，广播消息
                io.emit('addUser', data)

                // 告诉所有用户，当前聊天室用户列表以及数量
                io.emit('userList', chatRoomUsers)

                // 把登陆成功的用户信息存储起来
                socket.username = data.username
                socket.avatar = data.avatar
            }
        }
    })

    socket.on('logout', () => {
        io.emit('deleteUser', {
            username: socket.username,
            avatar: socket.avatar
        })
        // 把当前用户信息从 chat room 中删除
        leaveFromChatRoom(socket)
    })

    //监听聊天的消息
    socket.on('sendMessage', data => {
        //广播给所有用户
        io.emit('receiveMessage', data)
    })

    //接受图片的信息
    socket.on('sendImage', data => {
        //广播给所有用户
        io.emit('receiveImage', data)
    })
})

const leaveFromChatRoom = (data) => {
    let idx = chatRoomUsers.findIndex(item => item.username === data.username)
    if (idx > -1) {
        // 删除掉断开连接的人
        chatRoomUsers.splice(idx, 1)
    }
}

log(`应用实例，访问地址为 http://localhost:3000`)
server.listen(3000)
